import UIKit
import AFNetworking
import SVProgressHUD
class HomeViewController: BaseViewController {

    var refreshView: BreakOutToRefreshView!
    //模型数组
    private lazy var statusListViewModel = StatusListViewModel()
    //cellID
    private let homeCellId = "homeCellId"
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !userlogin {
            //用户没有登录 当前的根视图是访客视图 就不要设置tableView
            //设置访客视图的信息
            visitorLoginView?.setupInfoWith("关注一些人，回这里看看有什么惊喜", imageName: nil)
            return
        }
        prepareForTableView()
        //加载数据
        loadData()
        StartGame()
  
    }
    
    private func StartGame() {
        _ = CGFloat(100)
        refreshView = BreakOutToRefreshView(scrollView: tableView)
        refreshView.delegate = self
        
        // configure the colors of the refresh view
        refreshView.scenebackgroundColor = UIColor(hue: 0, saturation: 0, brightness: 1, alpha: 1.0)
        refreshView.paddleColor = UIColor.lightGrayColor()
        refreshView.ballColor = UIColor.blackColor()
        refreshView.blockColors = [UIColor(hue: 0.9, saturation: 0.9, brightness: 0, alpha: 1), UIColor(hue: 0.9, saturation: 0.7, brightness: 0, alpha: 1), UIColor(hue: 0.17, saturation: 1, brightness: 0, alpha: 1)]
        
        tableView.addSubview(refreshView)

    }
    private func prepareForTableView() {
        //注册cell
        tableView.registerClass(StatusCell.self, forCellReuseIdentifier: homeCellId)
        //设置cell的高度
        //要使用tableView能够自动计算行高需要设置两个属性
        //1.设置预估行高  尽量要接近真实的行高
        tableView.estimatedRowHeight = 300
        //2.设置行高为自动计算 (自动布局系统来计算行高) +  3.tableView的cell的contentView添加约束
        tableView.rowHeight = UITableViewAutomaticDimension
        //取消分割线
        tableView.separatorStyle = .None
        //设置小菊花为底部
        tableView.tableFooterView = indicatorView

//        indicatorView.startAnimating() : 不断加载BUG的根源
    }
   
    //MARK: 加载首页数据
    private func loadData() {
        
        //使用视图模型获取网络请求的结果 ->模型数组
        statusListViewModel.load(indicatorView.isAnimating()) { (isSuccess) -> () in
            if isSuccess {
                //请求数据成功
                self.tableView.reloadData()
            }else{
                 //请求数据失败
                SVProgressHUD.showErrorWithStatus("网络君正在睡觉,请稍后再试")
            }
        }
    }
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
    
}

extension HomeViewController: BreakOutToRefreshDelegate {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListViewModel.statues.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
           //使用这个方法 获取cell 手写代码的时候需要手动注册cell
        let cell = tableView.dequeueReusableCellWithIdentifier(homeCellId, forIndexPath: indexPath) as! StatusCell
        //        cell.textLabel?.text = statues[indexPath.row].user?.name
        if indexPath.row == statusListViewModel.statues.count - 1 && !indicatorView.isAnimating() {
            //小菊花开始转动  才会显示
            indicatorView.startAnimating()
            loadData()
        }
        //给cell的模型属性赋值
        cell.status = statusListViewModel.statues[indexPath.row]
        return cell
    }
    override func scrollViewDidScroll(scrollView: UIScrollView) {
        refreshView.scrollViewDidScroll(scrollView)
      
    }
    
    override func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        refreshView.scrollViewWillEndDragging(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset)
          loadData()
    }
    
    override func scrollViewWillBeginDragging(scrollView: UIScrollView) {
        refreshView.scrollViewWillBeginDragging(scrollView)
    }
    
    func refreshViewDidRefresh(refreshView: BreakOutToRefreshView) {
        // load stuff from the internet
        //停止动画
        self.refreshView.endRefreshing()
        //        self.tableView.reloadData()
        
    }

    
    
}